import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vischat/shared/widgets/view_list/state_widget.dart';
import 'package:vischat/shared/widgets/view_list/view_list_controller.dart';

class ViewList<T extends ViewListController<Item>, Item>
    extends StatelessWidget {
  final T controller;
  final bool autoLoad;
  final Widget Function() listBuilder;
  final Widget Function()? loadingWidget;
  final Widget Function()? emptyWidget;
  final Widget Function(String error)? errorWidget;
  final Widget Function()? loadMoreWidget;
  final Widget Function()? noMoreWidget;

  const ViewList({
    super.key,
    required this.controller,
    required this.listBuilder,
    this.loadingWidget,
    this.emptyWidget,
    this.errorWidget,
    this.loadMoreWidget,
    this.noMoreWidget,
    this.autoLoad = true,
  });

  @override
  Widget build(BuildContext context) {
    return GetX<T>(
      init: controller,
      autoRemove: false,
      builder: (controller) {
        return EasyRefresh(
          onRefresh: () => controller.load(isRefresh: true),
          onLoad: controller.hasMore.value ? () => controller.load() : null,
          header: ClassicHeader(
            showText: false,
          ),
          child: _buildStateWidget(controller),
        );
      },
    );
  }

  Widget _buildStateWidget(T controller) {
    return Obx(() {
      switch (controller.state.value) {
        case ViewState.busy:
          return loadingWidget?.call() ?? DefaultLoading();
        case ViewState.empty:
          return emptyWidget?.call() ?? DefaultEmpty();
        case ViewState.error:
          return errorWidget?.call(controller.errorMsg) ??
              DefaultError(
                error: controller.errorMsg,
                retry: () => controller.load(isRefresh: true),
              );
        case ViewState.idle:
          return Column(
            children: [
              Expanded(child: listBuilder()),
              _buildFooter(controller),
            ],
          );
      }
    });
  }

  Widget _buildFooter(T controller) {
    return Obx(() {
      if (!controller.hasMore.value && controller.list.isNotEmpty) {
        return noMoreWidget?.call() ?? DefaultNoMore();
      }
      return loadMoreWidget?.call() ?? DefaultLoadMore();
    });
  }
}
